package repositories

import (
	"SmartSearch/internal/models"
	"SmartSearch/internal/responses"
	"SmartSearch/pkg/database"
	"fmt"
	"gorm.io/gorm"
	"strconv"
)

type DepartmentRepository struct {
}

func (d *DepartmentRepository) Add(parentDepartment, department *models.Department) error {
	return database.DB.Transaction(func(tx *gorm.DB) error {
		if err := database.DB.Create(&department).Error; err != nil {
			return err
		}
		fmt.Printf("add department id is %d\n", department.Id)
		if parentDepartment != nil {
			department.Level = parentDepartment.Level + "/" + strconv.FormatInt(department.Id, 10)
		}
		if err := database.DB.Save(&department).Error; err != nil {
			return err
		}
		return nil
	})
}

func (d *DepartmentRepository) Del(id int64) error {
	return database.DB.Delete(&models.Department{}, id).Error
}

func (d *DepartmentRepository) FindById(id int64) (*models.Department, error) {
	var department models.Department
	err := database.DB.First(&department, id).Error
	return &department, err
}

// FindSonById 通过部门ID得到子部门列表
func (d *DepartmentRepository) FindSonById(id int64) ([]models.Department, error) {
	var sons []models.Department
	var department models.Department
	if err := database.DB.First(&department, id).Error; err != nil {
		return nil, err
	}
	err := database.DB.Where("level LIKE ?", department.Level+"%").Find(&sons).Error
	return sons, err
}

func (d *DepartmentRepository) FindByName(name string) (*models.Department, error) {
	department := &models.Department{}
	err := database.DB.Where("name = ?", name).First(department).Error
	return department, err
}

func (d *DepartmentRepository) FindList(name string, parentId int64, current int32, pageSize int32) *responses.Page {
	var total int64
	var data []*models.Department
	where := fmt.Sprintf("name LIKE '%s'", "%"+name+"%")
	if parentId < 0 {
		where += fmt.Sprintf(" AND parent_id = %d", parentId)
	}
	// 此处用了PostForm的请求方法
	tx := database.DB.Debug().Model(models.Department{}).Where(where) // 查询对应的数据库表
	// 此时的total是查询到的总数
	if err := tx.Count(&total).Error; err != nil {
		fmt.Println("获取总数错误" + err.Error())
		return nil
	}
	offset := (current - 1) * pageSize
	if err := tx.Order("id DESC").Offset(int(offset)).Limit(int(pageSize)).Find(&data).Error; err != nil {
		return nil
	}
	return &responses.Page{
		Current:  current,
		PageSize: pageSize,
		Total:    total,
		Content:  data,
	}
}

func (d *DepartmentRepository) Update(department *models.Department) error {
	return database.DB.Save(&department).Error
}
